<template>
  <div>
    <a-layout-header class="operateHeader">
      <a-button type="primary" class="addButton" @click="bindAdd">
        <svg
          t="1683356493274"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2398"
          width="20"
          height="20"
        >
          <path
            d="M543.890286 146.285714c5.705143 0 8.484571 2.706286 8.484571 8.118857v318.976h316.854857c5.632 0 8.484571 2.706286 8.484572 8.118858v61.001142c0 5.412571-2.852571 8.045714-8.484572 8.045715H552.374857v319.049143c0 5.412571-2.779429 8.118857-8.484571 8.118857h-63.780572c-5.705143 0-8.484571-2.706286-8.484571-8.118857l-0.073143-319.049143h-316.708571c-5.705143 0-8.557714-2.633143-8.557715-8.045715v-61.001142c0-5.412571 2.852571-8.045714 8.484572-8.045715l316.781714-0.073143v-318.902857c0-5.485714 2.925714-8.192 8.557714-8.192h63.780572z"
            fill="#ffffff"
            fill-opacity=".65"
            p-id="2399"
          ></path>
        </svg>
        添加路由
      </a-button>
      <a-input-search
        v-model:value="searchVal"
        placeholder="搜索路由地址"
        enter-button
        @search="onSearch"
        @change="bindAddress"
      />
    </a-layout-header>
    <a-layout-content>
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="{ total: totalNum, pageSizeOptions: pageSizeOptions }"
        @change="onShowSizeChange"
        :customRow="customRow"
        :loading="dataLoading"
      >
        <template #bodyCell="{ column }">
          <template v-if="column.dataIndex === 'operation'">
            <a-button type="primary" @click="bindEdit">编辑</a-button>
            <a-button type="danger " @click="bindDelete">删除</a-button>
          </template>
        </template>
      </a-table>
    </a-layout-content>
    <!-- 编辑对话框 -->
    <a-modal
      v-model:visible="visibleEdit"
      title="编辑路由"
      @ok="handleOk"
      @cancel="bindClose"
    >
      <a-input
        v-model:value="valueUrl"
        placeholder="Basic usage"
        style="margin-bottom: 20px"
      />
      <a-select
        v-model:value="editRole"
        mode="multiple"
        style="width: 100%"
        placeholder="设置权限"
        :options="options"
        @change="handleChangeEdit"
        option-label-prop="label"
      ></a-select>
    </a-modal>
    <!-- 删除对话框 -->
    <a-modal v-model:visible="visibleDel" title="删除路由" @ok="confirmDel">
      <p style="color: red">此操作无法回溯，请谨慎操作！！！！！</p>
    </a-modal>
    <!-- 添加对话框 -->
    <a-modal v-model:visible="visibleAdd" title="添加路由" @ok="confirmAdd">
      <a-input
        v-model:value="valueAddUrl"
        placeholder="路由地址"
        style="margin-bottom: 20px"
      />
      <div style="margin-bottom: 20px">
        <span>请求方式：</span>
        <a-select ref="select" v-model:value="valueSelAdd" style="width: 120px">
          <a-select-option value="GET">GET</a-select-option>
          <a-select-option value="POST">POST</a-select-option>
          <a-select-option value="PUT">PUT</a-select-option>
          <a-select-option value="DELETE">DELETE</a-select-option>
        </a-select>
      </div>
      <a-select
        v-model:value="valueGrade"
        mode="multiple"
        style="width: 100%"
        placeholder="设置权限"
        :options="options"
        @change="handleChangeAdd"
      ></a-select>
    </a-modal>
  </div>
</template>

<script setup>
import { defineComponent, onMounted, ref, watch } from "vue";
import { Myrequest } from "@/network/request";
import { message } from "ant-design-vue";
import loginVue from "../login/login.vue";
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: 90,
    align: "center",
  },
  {
    title: "路由地址",
    dataIndex: "url",
    align: "center",
    width: 350,
  },
  {
    title: "权限所有者",
    dataIndex: "role",
    width: 200,
    align: "center",
    customRender: ({ text }) => {
      // 在这里可以自定义渲染技能列的内容
      // 可以使用 text 访问技能数据
      return (
        <div>
          {text.map((item) => (
            <div>{item.rolename.name}</div>
          ))}
        </div>
      );
    },
  },
  {
    title: "请求方式",
    dataIndex: "method",
    align: "center",
    width: 120,
  },
  {
    title: "创建时间",
    dataIndex: "create_time",
    width: 200,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: 220,
    align: "center",
  },
];

    const data = ref([]); //数据源
    const totalNum = ref([]); //总条数
    const pageSizeOptions = ref(["5", "10", "15", "20"]); //一页选择展示多少数据
    const dataLoading = ref(false);
    function Refresh() {
      Myrequest("GET", "/admin/v1/routes", {
        keyword: "",
        page: "1",
        limit: 10,
      }).then((res) => {
        totalNum.value = res.data.total;
        data.value = res.data.data;
      });
    }
    // 搜索
    const searchVal = ref("");
    const onSearch = () => {
      Myrequest("GET", "/admin/v1/routes", {
        keyword: searchVal.value,
      }).then((res) => {
        data.value = res.data.data;
        totalNum.value = res.data.total;
        message.success("搜索到有：" + res.data.total + "条结果");
      });
    };
    // input的value为空时，调用Refresh
    const bindAddress = (e) => {
      console.log(e.srcElement.value);
      if (e.srcElement.value === "") {
        Refresh();
      }
    };

    // 点击页码展示数据
    const onShowSizeChange = (page, pageSize) => {
      Myrequest("GET", "/admin/v1/routes", {
        keyword: "",
        page: page.current,
        limit: page.pageSize,
      }).then((res) => {
        (data.value = res.data.data), (totalNum.value = res.data.total);
      });
    };

    // 首次渲染加载第一页数据
    onMounted(() => {
      Refresh();
    });

    // 点击行
    const visibleEdit = ref(false);
    const visibleDel = ref(false);
    const visibleAdd = ref(false);
    const valueUrl = ref("");
    const valueAddUrl = ref("");
    const editId = ref("");
    const editRole = ref([]);
    const editRoleStr = ref([]);
    const TeditRole = ref([]);
    const unique = (arr) => {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            arr.splice(j, 1);
            j--;
          }
        }
      }
    };
    const customRow = (record) => {
      return {
        onClick: (event) => {
          let FData = JSON.stringify(record);
          let SData = JSON.parse(FData);
          TeditRole.value = editRole.url;
          valueUrl.value = record.url;
          editId.value = SData.id;
        },
      };
    };
    const options = ref([
      {
        value: "1",
        label: "管理员",
      },
      {
        value: "2",
        label: "酒店管理员",
      },
      {
        value: "3",
        label: "用户",
      },
    ]);
    // 添加按钮
    const valueSelAdd = ref("");
    const valueGrade = ref([]);
    const valueG = ref("");
    const bindAdd = () => {
      visibleAdd.value = true;
    };
    const handleChangeAdd = (value) => {
      valueG.value = `${value}`;
      console.log(valueG.value);
    };
    const confirmAdd = () => {
      Myrequest("POST", "/admin/v1/routes", {
        url: valueAddUrl.value,
        method: valueSelAdd.value,
        roles: valueG.value,
      }).then((res) => {
        if (valueGrade.value.length === 0) {
          message.warning("权限设置不能为空，添加失败");
        } else {
          switch (res.code) {
            case 501:
              message.warning(res.msg);
              break;
            case 502:
              message.warning(res.msg);
              break;
            case 200:
              message.success("添加成功");
              visibleAdd.value = false;
              Refresh();
              valueAddUrl.value = "";
              valueSelAdd.value = "";
              valueG.value = "";
              valueGrade.value = [];
              break;
          }
        }
      });
    };
    // 编辑按钮
    const valueEdit = ref([]);
    const valueEditStr = ref("");
    const handleChangeEdit = (value, val) => {
      valueEditStr.value = `${value}`;
    };
    const bindClose = () => {
      editRole.value = [];
    };
    const bindEdit = (e) => {
      // 通过延迟以达到异步效果，获取数据
      setTimeout(() => {
        Myrequest("GET", "/admin/v1/routes/" + editId.value).then((res) => {
          res.data.role.forEach((item) => {
            editRole.value.push(String(item.role_id));
          });
        });
      }, 100);
      visibleEdit.value = true;
    };
    const handleOk = (e) => {
      Myrequest("PUT", "/admin/v1/routes/" + editId.value, {
        url: valueUrl.value,
        roles: valueEditStr.value,
      }).then((res) => {
        console.log(res);
        switch (res.code) {
          case 501:
            message.warning(res.msg);
            break;
          case 200:
            if (editRole.value.length === 0) {
              message.warning("权限设置不能为空");
            } else {
              message.success("修改成功");
              visibleEdit.value = false;
              // 强制页面刷新获取最新数据
              location.reload();
            }
            break;
        }
      });
    };

    // 删除按钮
    const bindDelete = () => {
      visibleDel.value = true;
    };
    const confirmDel = () => {
      Myrequest("DELETE", "/admin/v1/routes/" + editId.value).then((res) => {
        console.log(res);
        switch (res.code) {
          case 200:
            message.success("删除成功");
            Myrequest("GET", "/admin/v1/routes", {
              keyword: "",
              page: "1",
              limit: 10,
            }).then((res) => {
              (data.value = res.data.data), (totalNum.value = res.data.total);
            });
            break;
        }
      });

      visibleDel.value = false;
    };
</script>

<style lang="less">
.addButton {
  padding: 25px 20px;
  display: flex;
  align-items: center;
  margin-left: 45px;
  border-radius: 10px;
  svg {
    margin-right: 5px;
  }
}

.ant-layout-content {
  padding: 0 45px;
}
.operateHeader {
  background-color: #f0f2f5;
  padding: 0;
  display: flex;
  align-items: center;
  .ant-input-group-wrapper {
    width: 300px;
    margin-left: 100px;
    input {
      height: 50px;
    }
    .ant-btn-primary {
      width: 50px;
      height: 50px;
    }
  }
}
</style>